package com.lineage.server.timecontroller.npc;

import com.lineage.config.Config;
import com.lineage.server.datatables.NpcChatTable;
import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.templates.L1NpcChat;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.WorldNpc;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimeZone;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class NpcChatTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(NpcChatTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 60000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 60000L, 60000L);
  }
  
  public void run() {
    try {
      Collection<L1NpcChat> allChat = NpcChatTable.get().all();
      if (allChat.isEmpty())
        return; 
      Iterator<L1NpcChat> iter = allChat.iterator();
      while (iter.hasNext()) {
        L1NpcChat npcChat = iter.next();
        if (isChatTime(npcChat.getGameTime())) {
          int npcId = npcChat.getNpcId();
          Iterator<L1NpcInstance> iterator = WorldNpc.get().all().iterator();
          while (iterator.hasNext()) {
            L1NpcInstance npc = iterator.next();
            if (npc.getNpcTemplate().get_npcId() == npcId)
              npc.startChat(3); 
          } 
        } 
        Thread.sleep(50L);
      } 
    } catch (Exception e) {
      _log.error("NPC对话时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      NpcChatTimer npcChatTimer = new NpcChatTimer();
      npcChatTimer.start();
    } 
  }
  
  private boolean isChatTime(int chatTime) {
    SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
    Calendar realTime = getRealTime();
    int nowTime = Integer.valueOf(sdf.format(realTime.getTime())).intValue();
    return (nowTime == chatTime);
  }
  
  private static Calendar getRealTime() {
    TimeZone _tz = TimeZone.getTimeZone(Config.TIME_ZONE);
    Calendar cal = Calendar.getInstance(_tz);
    return cal;
  }
}
